using Abp.Application.Services.Dto;
using Abp.Authorization;
using Abp.AutoMapper;
using Abp.Linq.Extensions;
using Abp.Extensions;
using Abp.Domain.Repositories;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using SOEI.Solution.Application;
using SOEI.Solution;
using SOEI.Solution.Integratedes.ElectronicSignet;
using SOEI.Solution.Integratedes.ElectronicSignet.DomainService;
using SOEI.Solution.Integratedes.ElectronicSignet.Dtos;


using SOEI.Solution.Authorization;
using SOEI.Solution.StructEntities.Organization;
using SOEI.Solution.Customized.Dtos;
using SOEI.Solution.Customized;
using Abp.Timing;
using SOEI.Solution.Integratedes.Organization.DomainService;
using SOEI.Solution.Helper;
using SOEI.Solution.ThirdParty.ESignClient.Models;
using Abp.UI;

namespace SOEI.Solution.Integratedes.ElectronicSignet
{
	/// <summary>
	/// 【扩展模块】  <br/>
	/// 【功能描述】  ：电子印章授权(使用中)<br/>
	/// 【创建日期】  ：2020.05.21 <br/>
	/// 【开发人员】  ：static残影<br/>
	///</summary>
	[ApiExplorerSettings(GroupName = "Manager", IgnoreApi = false)]
	public class OursSignetGrantAppService : SolutionAppServiceBase, IOursSignetGrantAppService
	{
		/// <summary>
		///【SignetGrant】仓储层
		/// </summary>
		private readonly IRepository<SignetGrant, long>	_signetgrantRepository;

		/// <summary>
		///【SignetGrant】领域服务
		/// </summary>
		private readonly ISignetGrantManager _signetgrantManager;

		/// <summary>
		///【机构人员】机构人员领域
		/// </summary>
		private readonly IOEconomyPersonManager _oeconomypersonManager;

		public OursSignetGrantAppService(
			IRepository<SignetGrant, long>  signetgrantRepository,
			ISignetGrantManager signetgrantManager,
			IOEconomyPersonManager oeconomypersonManager
		)
		{
			_signetgrantRepository = signetgrantRepository;
			_signetgrantManager = signetgrantManager;
			_oeconomypersonManager = oeconomypersonManager;
		}
		
		#region -------------------------------------------------辅助工具生成---------------------------------------------- 
		
		/// <summary>
		///【SignetGrant】获取的分页列表信息
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		//[AbpAuthorize(SignetGrantPermissions.Node)]
		public async Task<PagedResultDto<SignetGrantListDto>> GetPaged(GetSignetGrantsInput input)
		{
			var query = this._signetgrantRepository.GetAll()
							//模糊搜索 字段RYBH
						  .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.RYBH.Contains(input.FilterText))                                                                                      
							//模糊搜索 字段SQZT
						  .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.SQZT.Contains(input.FilterText))                                                                                      
			;
			// TODO:根据传入的参数添加过滤条件

			var count = await query.CountAsync();

			var entityList = await query
					.OrderBy(input.Sorting).AsNoTracking()
					.PageBy(input)
					.ToListAsync();

			var entityListDtos = ObjectMapper.Map<List<SignetGrantListDto>>(entityList);

			return new PagedResultDto<SignetGrantListDto>(count,entityListDtos);
		}

		/// <summary>
		///【SignetGrant】通过指定id获取MemberListDto信息
		/// </summary>
		//[AbpAuthorize(SignetGrantPermissions.Node)]
		public async Task<SignetGrantListDto> GetById(EntityDto<long> input)
		{
			var entity = await _signetgrantRepository.GetAsync(input.Id);

			var dto = ObjectMapper.Map<SignetGrantListDto>(entity);
			return dto;
		}

		/// <summary>
		///【SignetGrant】 获取编辑
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		//[AbpAuthorize(SignetGrantPermissions.Node)]
		public async Task<GetSignetGrantForEditOutput> GetForEdit(NullableIdDto<long> input)
		{
			var output = new GetSignetGrantForEditOutput();
			SignetGrantEditDto editDto;

			if (input.Id.HasValue)
			{
				var entity = await _signetgrantRepository.GetAsync(input.Id.Value);
				editDto = ObjectMapper.Map<SignetGrantEditDto>(entity);
			}
			else
			{
				editDto = new SignetGrantEditDto();
			}
			output.SignetGrant = editDto;
			return output;
		}

		/// <summary>
		///【SignetGrant】 添加或者修改的公共方法
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		//[AbpAuthorize(SignetGrantPermissions.Node)]
		public async Task CreateOrUpdate(CreateOrUpdateSignetGrantInput input)
		{
			if (input.SignetGrant.Id.HasValue)
			{
				await Update(input.SignetGrant);
			}
			else
			{
				await Create(input.SignetGrant);
			}
		}
		/// <summary>
		///【SignetGrant】新增
		/// </summary>
		//[AbpAuthorize(SignetGrantPermissions.Node)]
		protected virtual async Task<SignetGrantEditDto> Create(SignetGrantEditDto input)
		{
			//TODO:新增前的逻辑判断，是否允许新增

			var entity = ObjectMapper.Map<SignetGrant>(input);


			// 找到人员信息
			var personEntity = await this._oeconomypersonManager.FindByIdAsync(entity.RYBH);
			// 生成账号实体
			var Account = personEntity.ToAccountEntity();

			var AccountModel = await this._signetgrantManager.GetAccountModel(entity, Account);

			entity.AccountID = AccountModel.AccountID;

			//调用领域服务
			entity = await _signetgrantManager.CreateAsync(entity);
			

			var dto=ObjectMapper.Map<SignetGrantEditDto>(entity);
			return dto;
		}

		/// <summary>
		///【SignetGrant】编辑
		/// </summary>
		//[AbpAuthorize(SignetGrantPermissions.Node)]
		protected virtual async Task Update(SignetGrantEditDto input)
		{
			//TODO:更新前的逻辑判断，是否允许更新
			var key =  input.Id.Value;
			var entity = await _signetgrantRepository.GetAsync(key);
			//  input.MapTo(entity);
			//将input属性的值赋值到entity中
			ObjectMapper.Map(input, entity);

			// 找到人员信息
			var personEntity = await this._oeconomypersonManager.FindByIdAsync(entity.RYBH);
			// 生成账号实体
			var Account = personEntity.ToAccountEntity();

			var AccountModel =  await this._signetgrantManager.GetAccountModel(entity, Account);

			entity.AccountID = AccountModel.AccountID;

			// 更新
			await _signetgrantManager.UpdateAsync(entity);
		}

		/// <summary>
		///【SignetGrant】删除信息
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		//[AbpAuthorize(SignetGrantPermissions.Node)]
		public async Task Delete(EntityDto<long> input)
		{
			//TODO:删除前的逻辑判断，是否允许删除
			await _signetgrantManager.DeleteAsync(input.Id);
		}

		/// <summary>
		///【SignetGrant】 批量删除Member的方法
		/// </summary>
		//[AbpAuthorize(SignetGrantPermissions.Node)]
		public async Task BatchDelete(List<long> input)
		{
			// TODO:批量删除前的逻辑判断，是否允许删除
			await _signetgrantManager.BatchDelete(input);
		}

		#endregion

		#region -------------------------------------------------用户自定义------------------------------------------------
		/*请在此扩展应用服务实现*/

		/// <summary>
		///【印章授权】用户印章授权列表清单（带分页）
		/// </summary>
		/// <param name="input">人员编号</param>
		/// <returns></returns>
		public async Task<PagedResultDto<OurOrganiPerson>> GetSignetGrantPaged(GetSignetGrantsInput input)
		{
			var userEntity = await this.GetPersonChecker();

			var query = this._signetgrantManager.QueryUnionEntityListAsNoTracking()
						  //模糊搜索 字段RYBH
						  .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.RYMC.Contains(input.FilterText) || a.SFZH.Contains(input.FilterText) || a.LXDH.Contains(input.FilterText))
						  .Where(x => x.JGBH == userEntity.OriginalNumber) // 只获取自己机构的
			;
			// TODO:根据传入的参数添加过滤条件

			var count = await query.CountAsync();

			var entityList = await query
					.OrderBy(input.Sorting).AsNoTracking()
					.PageBy(input)
					.ToListAsync();

			//var entityListDtos = ObjectMapper.Map<List<SignetGrantListDto>>(entityList);

			return new PagedResultDto<OurOrganiPerson>(count, entityList);
		}

		/// <summary>
		///【SignetGrant】 获取编辑
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		//[AbpAuthorize(SignetGrantPermissions.Node)]
		public async Task<GetSignetGrantForEditOutput> GetForGrant(SignetGrantInput input)
		{
			var userEntity = await this.GetPersonChecker();
			var output = new GetSignetGrantForEditOutput();
			SignetGrantEditDto editDto;
			
			if (input.Id.HasValue)
			{
				// 如果存在授权直接获取
				var entity = await _signetgrantRepository.GetAsync(input.Id.Value);
				editDto = ObjectMapper.Map<SignetGrantEditDto>(entity);
			}
			else
			{
				// 不存在创建一个新的
				editDto = new SignetGrantEditDto();
				editDto.SQZT = ((int)EApprovalStatus.WaitSubmit).ToString();
				editDto.RYBH = input.RYBH;
				editDto.SXRQ = Clock.Now;
				editDto.JGBH = userEntity.OriginalNumber;
				editDto.Remark = string.Empty;
			}
			output.SignetGrant = editDto;
			return output;
		}

		/// <summary>
		/// 获取E签宝账号信息根据电子签章编号
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		public async Task<AccountModel> GetForAccount(EntityDto<long> input)
		{
			var userEntity = await this.GetPersonChecker();

			var entity = await _signetgrantRepository.GetAsync(input.Id);

			// 找到人员信息
			var personEntity = await this._oeconomypersonManager.FindByIdAsync(entity.RYBH);
			// 生成账号实体
			var Account = personEntity.ToAccountEntity();

			var AccountModel = await this._signetgrantManager.GetAccountModel(entity, Account);

			return AccountModel;
		}

		#endregion

		#region -------------------------------------------------辅助程序------------------------------------------------

		

		#endregion
	}
}
